from flask import render_template, jsonify, request, session

from models import db
from models.index import News, User
from views import index_bp


@index_bp.route('/')
def index():
    clicks_top_6_news = db.session.query(News).order_by(-News.clicks).limit(6)
    user_id = session.get("user_id", 0)
    if user_id:
        user_name = db.session.query(User).filter(User.id == user_id).first()
        nick_name = user_name.nick_name
    else:
        nick_name = None

    return render_template('index/index.html', clicks_top_6_news=clicks_top_6_news, nick_name=nick_name)


@index_bp.route('/newslist')
def category_news():
    # return '返回新闻数据'
    page = request.args.get('page', 1)
    cid = int(request.args.get('cid', 0))

    per_page = request.args.get('per_page', 1)
    # 如果cid是0，表示要看最新的，如果不是0则按照原来规则查询
    if cid == 0:
        paginate = db.session.query(News).order_by(-News.update_time).paginate(page=int(page), per_page=int(per_page),
                                                                               error_out=False)
    else:
        cid += 1  # 由于测试数据分类中从0开始，而数据库中是从1开始的，所以用户点击的1实际上是2
        paginate = db.session.query(News).filter(News.category_id == cid).paginate(page=int(page),
                                                                                   per_page=int(per_page),
                                                                                   error_out=False)

    # paginate = db.session.query(News).paginate(page=int(page), per_page=int(per_page), error_out=False)
    ret = {
        "totalPage": paginate.pages,
        "newsList": [news.to_dict() for news in paginate.items]
    }

    # 4. 遍历当前页中新闻信息,最终的目的取新闻对象中的属性，将其封装到字典中

    # 5. 将ret字典转换为json样子的字符串，返回
    return jsonify(ret)


@index_bp.route('/detail/<int:news_id>')
def detail(news_id):
    news = db.session.query(News).filter(News.id == news_id).first()
    news_author = news.user
    news_author.news_num = news_author.news.count()
    news_author.follwer_num = news_author.followers.count()

    # 查询用户是否已经登录
    user_id = session.get("user_id", 0)

    if user_id:
        user_name = db.session.query(User).filter(User.id == user_id).first()
        nick_name = user_name.nick_name
    else:
        nick_name = None

    # 计算当前登录用户是否已经关注了这个新闻的作者
    news_author_followers_id = [x.id for x in news_author.followers]
    if user_id in news_author_followers_id:
        news_author.can_follow = False  # 已经关注了作者，就不能在关注了
    else:
        news_author.can_follow = True  # 可以关注
    return render_template('index/detail.html', news=news, nick_name=nick_name, news_author=news_author)
